<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="拥有的菜单权限" width="550px" destroyOnClose showFooter>
    <!-- toolbar -->
    <BasicTree
      ref="treeRef"
      checkable
      :toolbarOptions="toolbarOptions"
      :treeData="state.treeData"
      :checkedKeys="state.checkedKeys"
      :selectedKeys="state.selectedKeys"
      :clickRowToExpand="false"
      :checkStrictly="false"
      :defaultExpandLevel="2"
      @check="onCheck"
      @select="onTreeNodeSelect"
    >
      <template #title="{ title, menuType, apiActions }">
        <span>{{ title }}</span>
        <div v-if="apiActions.length > 0">
          <Tooltip placement="top">
            <template #title>
              <span v-for="item in apiActions" :key="item">
                {{ item }} <br/>
              </span>
            </template>
            <Icon icon="i-ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
          </Tooltip>
        
        </div>
        
      </template>
    </BasicTree>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted, toRaw } from "vue"
  import { Tooltip } from "ant-design-vue"
  import { BasicTree, TreeItem, TreeActionType, ToolbarEnum } from "/@/components/Tree"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import * as permPolicyApi  from "/@/api/iam/permPolicy"
  import * as UserApi  from "/@/api/sys/user"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Icon } from "/@/components/Icon"
  const { createMessage } = useMessage()
  const toolbarOptions = ref<ToolbarEnum[]>([ToolbarEnum.EXPAND_ALL, ToolbarEnum.UN_EXPAND_ALL, ToolbarEnum.SELECT_ALL, ToolbarEnum.UN_SELECT_ALL])

  const emit = defineEmits(["register"])

  interface State {
    // 树的信息
    treeData: TreeItem[]
    // 树的全部节点信息
    allTreeKeys: any[]
    //树的选择节点信息
    checkedKeys: any[]
    halfCheckedKeys: any[]
    defaultCheckedKeys: any[]
    //树的选中的节点信息
    selectedKeys: any[],
    userId?: any
  }

  const state = ref<State>({
    treeData: [],
    allTreeKeys: [],
    checkedKeys: [],
    halfCheckedKeys: [],
    defaultCheckedKeys: [],
    selectedKeys: [],
    userId: null,
  })

  const stateValue = state.value
  const treeRef = ref<TreeActionType>()
  const loading = ref(false)

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      console.log('data', data)
      await initMenuPermission(data.userId)
    } finally {
      setDrawerProps({ loading: false })
    }
  })


  const initMenuPermission = async (userId) => {
    stateValue.userId = userId

    //初始化菜单数据
    stateValue.treeData = await permPolicyApi.listSubjectMenuTree({ subjectId:userId  })
    stateValue.allTreeKeys = stateValue.treeData.map((e) => e.id)

    // const permResult = await UserApi.listPermission({ subjectId: stateValue.userId })
    // stateValue.checkedKeys = permResult.map((e) => e.menuId)
    // stateValue.defaultCheckedKeys = permResult.map((e) => e.menuId)
  }


  function onCheck(o) {
    stateValue.halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || []
    stateValue.checkedKeys = o.checked ? o.checked : o
  }

  function onTreeNodeSelect(key) {
    if (key && key.length > 0) {
      stateValue.selectedKeys = key
    }
    const menuId = toRaw(stateValue.selectedKeys)[0]
  }

  function reset() {
    stateValue.treeData = []
    stateValue.allTreeKeys = []
    stateValue.checkedKeys = []
    stateValue.defaultCheckedKeys = []
    stateValue.selectedKeys = []
  }

  async function handleSubmit() {
    loading.value = true
    try {
      const { userId } = unref(state)

      let params = {
        userId: userId,
        // @ts-ignore
        permissionIds: toRaw(treeRef.value?.getCheckedKeys()).join(","),
        // lastPermissionIds: toRaw(stateValue.defaultCheckedKeys).join(","),
      }
      await UserApi.saveUserPermission(params)
      createMessage.success("授权成功")
    } finally {
      loading.value = false
    }
  }
</script>
